package cn.stylefeng.guns.modular.business.app.controller;

import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.app.RyController;
import cn.stylefeng.guns.modular.business.frequency.finance.service.FinanceService;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderVO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.OrderProgressVO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSubBase;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgTransportLevelDetailSimple;
import cn.stylefeng.guns.modular.business.frequency.ordersub.service.OrderSubService;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.sys.modular.user.entity.EnterpriseUserMsg;
import cn.stylefeng.guns.sys.modular.user.mapper.EnterpriseUserMsgMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 订单相关
 *
 * @author liuyao
 */
@Deprecated
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends RyController {

    @Resource
    private OrderSubService orderSubService;
    @Resource
    private FinanceService financeService;
    @Resource
    private FinanceDetailMapper financeDetailMapper;
    @Autowired
    private BusinessUtil businessUtil;


    @ApiOperation(value = "创建订单")
    @PostMapping
    public ResponseData createOrder(@RequestBody @Validated OrderVO orderVO) {
        log.info("创建订单参数：{}", orderVO);
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkOrderCreate(orderVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.createOrder(orderVO);
        return ResponseData.andaSuccess();
    }

    //@NoRepeatSubmit
    @ApiOperation(value = "修改订单")
    @PutMapping
    public ResponseData updateOrder(@RequestBody @Validated OrderVO orderVO) {
        log.info("修改订单参数：{}", orderVO);
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkOrderUpdate(orderVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.updateOrder(orderVO);
        return ResponseData.andaSuccess("RETURN_SUCCESS");
    }


    @ApiOperation(value = "订单分页列表")
    @GetMapping
    public ResponseData getOrderListPage(OrderDTO orderDTO) {
        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        // 数据权限处理
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setUserIdList(empByOrgList);
        return orderSubService.getOrderListPage(orderDTO);
    }

    @Autowired
    private EnterpriseUserMsgMapper enterpriseUserMsgMapper;

    @ApiOperation(value = "订单详情")
    @GetMapping("/{id}")
    public ResponseData getOrderDetail(@PathVariable Long id,
                                       @RequestParam(value = "scene", required = false, defaultValue = "1")
                                       @ApiParam(name = "scene", value = "使用场景 1.订单详情（默认） 2.提车 3.签收 4.送车 ") Integer scene,
                                       @RequestParam(value = "transportId", required = false) Long transportId) {
        PkgOrderSub orderSub = orderSubService.getOrderDetail(id, scene, transportId);
        EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectOne(new LambdaQueryWrapper<EnterpriseUserMsg>()
                .eq(EnterpriseUserMsg::getTenantId, orderSub.getTenantId()));
        if (enterpriseUserMsg != null) {
            orderSub.setIsOpen("1");
        } else {
            orderSub.setIsOpen("2");
        }
        return ResponseData.success(orderSub);
    }

    @ApiOperation(value = "编辑订单详情")
    @GetMapping("/update/detail")
    public ResponseData getOrderVOByOrderIds(@RequestParam("ids") Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        OrderVO orderVO = orderSubService.getOrderVOByOrderIdList(idList);
        return ResponseData.andaSuccess(orderVO);
    }


    @ApiOperation(value = "子订单状态进度条")
    @GetMapping("/status/{id}")
    public ResponseData getSubOrderStatus(@PathVariable String id) {
        OrderProgressVO progress = orderSubService.getSubOrderStatus(id);
        return ResponseData.success(progress);
    }

    @ApiOperation(value = "订单修改记录详情列表")
    @GetMapping("/{id}/modify-record")
    public ResponseData getOrderModifyRecord(@PathVariable Long id) {
        List<OrderModifyDetail> list = orderSubService.getOrderModifyRecord(id);
        return ResponseData.success(list);
    }

    @ApiOperation(value = "批量获取订单信息")
    @GetMapping("/multi/infos")
    public ResponseData getOrderInfos(@RequestParam("orderIds") List<Long> orderIds) {
        List<PkgOrderSubBase> list = orderSubService.getOrderInfos(orderIds);
        return ResponseData.success(list);
    }


    @ApiOperation(value = "批量取消订单")
    @PostMapping("/cancel")
    public ResponseData multiCancel(@RequestBody String[] ids) {
        List<String> idList = Arrays.asList(ids);
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkMultiCancel(idList, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.multiCancel(idList);
        return ResponseData.success();
    }

    @PutMapping("/finance")
    @ApiOperation(value = "订单财务数据修改")
    public ResponseData orderFinanceUpdate(@RequestBody OrderSub orderSub) {
        StringBuilder errorMsg = new StringBuilder();
        if (!orderSubService.checkOrderFinanceUpdate(orderSub, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        orderSubService.orderFinanceUpdate(orderSub);
        financeService.changeFinanceStatus(orderSub.getId());
        return ResponseData.success();
    }

    @ApiOperation(value = "订单发运成本编辑")
    @PutMapping("/transport-cost")
    public ResponseData updateOrderTransportCost(@RequestBody PkgTransportLevelDetailSimple orderTransport) {
        if (orderTransport == null || orderTransport.getOrderId() == null ||
                orderTransport.getTransportSimple().getId() == null || orderTransport.getCost() == null) {
            return ResponseData.andaError("参数错误！");
        }
        FinanceDetail fd = financeDetailMapper.getByOrderIdAndRelationId(8, orderTransport.getOrderId(), orderTransport.getTransportSimple()
                .getId());
        if (fd != null && orderTransport.getCost().compareTo(fd.getHasSettlement()) < 0) {
            return ResponseData.andaError("费用不可小于已经结算的金额");
        }
        orderSubService.updateOrderTransportCost(orderTransport);
        return ResponseData.success();
    }


    @ApiOperation(value = "修改车架号")
    @PutMapping("/vin")
    public ResponseData updateVin(@RequestBody OrderSub orderSub) {
        if (orderSub == null || orderSub.getId() == null || StringUtils.isEmpty(orderSub.getVin())) {
            return ResponseData.andaError("参数错误");
        }
        orderSubService.updateVin(orderSub.getId(), orderSub.getVin());
        return ResponseData.success();
    }

}
